/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年12月17日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.practice;

import java.util.Arrays;

/**
 * @Type A20191217_heapsort
 * @Desc
 * @author 52489
 * @date 2019年12月17日
 * @Version V1.0
 */
public class A20191217_heapsort {
    public static void main(String[] args) {
        int num[] = { 3, 2, 1, 7, 8, 4, 6, 5 };
        heapsort(num);
    }

    /**
     * @param num
     */
    private static void heapsort(int[] num) {
        for (int i = num.length / 2 - 1; i >= 0; i--) {
            ajustHeap(num, i, num.length - 1);
        }
        System.out.println(Arrays.toString(num));

        for (int i = num.length - 1; i > 0; i--) {
            int tmp = num[0];
            num[0] = num[i];
            num[i] = tmp;
            ajustHeap(num, 0, i - 1);
        }

        System.out.println(Arrays.toString(num));

    }

    /**
     * @param num
     * @param i
     * @param j
     */
    private static void ajustHeap(int[] num, int i, int j) {
        if (2 * i + 1 <= j) {
            int tmp = num[i];
            int maxChildIdx = 2 * i + 1;
            if (maxChildIdx + 1 < j && num[maxChildIdx + 1] > num[maxChildIdx]) {
                maxChildIdx++;
            }

            if (num[maxChildIdx] > tmp) {
                num[i] = num[maxChildIdx];
                num[maxChildIdx] = tmp;
                ajustHeap(num, maxChildIdx, j);
            }

        }
    }

    private static void ajustHeap1(int[] num, int i, int j) {
        while (2 * i + 1 <= j) {
            int tmp = num[i];
            int maxChildIdx = 2 * i + 1;
            if (maxChildIdx + 1 < j && num[maxChildIdx + 1] > num[maxChildIdx]) {
                maxChildIdx++;
            }
            if (num[maxChildIdx] > tmp) {
                num[i] = num[maxChildIdx];
                num[maxChildIdx] = tmp;
                i = maxChildIdx;
            } else {
                break;
            }
        }
    }

}
